package com.gaojiabao.panghu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaojiabao.panghu.constant.ResultCodeEnum;
import com.gaojiabao.panghu.data.dto.ConditionDto;
import com.gaojiabao.panghu.data.pojo.Community;
import com.gaojiabao.panghu.data.vo.SelectCommunityOptionVo;
import com.gaojiabao.panghu.mapper.CommunityMapper;
import com.gaojiabao.panghu.service.CommunityService;
import com.gaojiabao.panghu.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: gaojiabao
 * @Date: 2024/11/3 16:01
 */
@Service
public class CommunityServiceImpl implements CommunityService {
    @Resource
    private CommunityMapper communityMapper;

    //分页查询小区数据
    @Override
    public Result<?> getCommunityList(Integer currentPage, Integer pageSize, ConditionDto conditionDto) {
        //分页参数是否正确
        if (currentPage == 0 || pageSize == 0) {
            return Result.build(ResultCodeEnum.PATH_PARAM_ERROR);
        }

        LambdaQueryWrapper<Community> queryWrapper = new LambdaQueryWrapper<>();
        if (null != conditionDto) {
            //条件查询SQL
            if (!conditionDto.getKeyWord().isBlank())
                queryWrapper.like(Community::getCommunityName, conditionDto.getKeyWord());
            if (conditionDto.getPreDate() != null)
                queryWrapper.ge(Community::getCreateTime, conditionDto.getPreDate());
            if (conditionDto.getPostData() != null)
                queryWrapper.le(Community::getCreateTime, conditionDto.getPostData());
        }
        queryWrapper.orderByDesc(Community::getId);

        //分页查询小区数据
        Page<Community> selectPage = new Page<>(currentPage, pageSize);
        Page<Community> communityPageList = communityMapper.selectPage(selectPage, queryWrapper);
        return Result.ok(communityPageList);
    }

    //根据id查询小区的数据
    @Override
    public Result<?> getCommunityById(String id) {
        //检查参数
        if (!validateParameter(id)) {
            return Result.build(ResultCodeEnum.PATH_PARAM_ERROR);
        }

        //检查小区id是否存在
        Community community = communityMapper.selectById(Integer.valueOf(id));
        if (community == null) {
            return Result.build(ResultCodeEnum.COMMUNITY_NO_ID);
        }
        return Result.ok(community);
    }

    //根据id逻辑删除小区数据
    @Override
    @Transactional
    public Result<?> deleteCommunityById(String id) {
        //检查参数
        if (!validateParameter(id)) {
            return Result.build(ResultCodeEnum.PATH_PARAM_ERROR);
        }

        //检验小区是否存在
        if (!existCommunity(Integer.valueOf(id))) {
            return Result.build(ResultCodeEnum.COMMUNITY_NO_ID);
        }

        //添加修改时间
        LambdaUpdateWrapper<Community> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Community::getId, Integer.valueOf(id))
                .set(Community::getDeleteTime, LocalDateTime.now());
        communityMapper.update(updateWrapper);

        //检查是否删除成功
        int row = communityMapper.deleteById(Integer.valueOf(id));
        if (row > 0) {
            return Result.ok();
        } else {
            return Result.build(ResultCodeEnum.COMMUNITY_DELETE_ERROR);
        }
    }

    //编辑小区
    @Override
    @Transactional
    public Result<?> updateCommunity(Community community) {
        //id查询修改
        LambdaUpdateWrapper<Community> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Community::getId, community.getId())
                .set(Community::getCommunityName, community.getCommunityName())
                .set(Community::getFullAddress, community.getFullAddress())
                .set(Community::getSimpleAddress, community.getSimpleAddress())
                .set(Community::getCoordinate, community.getCoordinate())
                .set(Community::getProvince, community.getProvince())
                .set(Community::getCity, community.getCity())
                .set(Community::getDistrict, community.getDistrict());

        //判断是否修改成功
        int row = communityMapper.update(updateWrapper);
        if (row > 0) {
            return Result.ok();
        } else {
            return Result.build(ResultCodeEnum.COMMUNITY_UPDATE_ERROR);
        }
    }

    //新增小区
    @Override
    @Transactional
    public Result<?> addCommunity(Community community) {
        //新增社区创建时间
        community.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));

        int row = communityMapper.insert(community);
        if (row > 0)
            return Result.ok();
        else
            return Result.build(ResultCodeEnum.COMMUNITY_ADD_ERROR);
    }

    //社区下拉框数据
    @Override
    public Result<?> selectOption() {
        LambdaQueryWrapper<Community> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Community::getId, Community::getCommunityName)
                .orderByDesc(Community::getId);
        List<Community> communityList = communityMapper.selectList(queryWrapper);

        //数组的map高级用法：
        //1.先使用 stream() 方法创建一个流，
        //2.然后使用 map() 方法转换每个 Community 对象为 SelectCommunityOptionVo 对象，
        //3.最后使用 collect() 方法收集结果到一个新的列表中。
        List<SelectCommunityOptionVo> optionVoList = communityList.stream()
                .map(item -> new SelectCommunityOptionVo(item.getId(), item.getCommunityName()))
                .collect(Collectors.toList());
        return Result.ok(optionVoList);
    }

    /*=========================================================*/


    //提取方法——检验参数是否为整数
    public Boolean validateParameter(String id) {
        //检查参数
        return org.apache.commons.lang3.StringUtils.isNumeric(id);
    }

    //提取方法——检查该id的小区是否存在
    public Boolean existCommunity(Integer id) {
        Community community = communityMapper.selectById(id);
        return community != null;
    }
}
